package com.meteor.web.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.meteor.pojo.Type;
import com.meteor.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Resource
    private TypeService typeService;

    /**
     * 分页-跳转到分类主页面
     */
    @GetMapping("/types/{pageNum}")
    public String queryTypes(@PathVariable Integer pageNum, Model model) {
        PageHelper.startPage(pageNum,5);
        List<Type> types = typeService.queryTypes();
        PageInfo<Type> pageInfo = new PageInfo<>(types);
        model.addAttribute("types",types);
        model.addAttribute("page",pageInfo);
        return "admin/types";
    }

    /**
     * 跳转新增分类页面
     */

    @GetMapping("/types/input")
    public String typesInput() {
        return "admin/types-input";
    }

    /**
     * 新增分类功能实现
     */
    @PostMapping("/types")
    public String addType(Type type, RedirectAttributes attributes) {
        Type[] ty = typeService.queryTypeByName(type.getName());
        if(ty.length == 0) {
            //没有重复的name
            int i = typeService.addType(type);
            if(i <= 0) {
                attributes.addFlashAttribute("message","抱歉，您操作失败！");
            }else {
                attributes.addFlashAttribute("message","恭喜您，操作成功！");
            }
        }else {
            //name重复了
            attributes.addFlashAttribute("message","抱歉您输入的名字已经存在");
        }
        return "redirect:/admin/types/1";
    }

    /**
     * 编辑功能
     */
    @GetMapping("/types/{id}/input")
    public String queryTypeById(@PathVariable Integer id, HttpSession session,Model model) {
        Type type = typeService.queryTypeById(id);
        session.setAttribute("type",type);
        model.addAttribute("type",type);
        return "admin/types-update";
    }
    @GetMapping("/types-update")
    public String updateTypeByIdAndName(Type types,HttpSession session) {
        Type type = (Type)session.getAttribute("type");
        int i = typeService.updateTypeByIdAndName(types.getName(), type.getId());
        return "redirect:/admin/types/1";
    }

    /**
     * 根据id删除分类
     */
    @GetMapping("/types/{id}/delete")
    public String deleteTypeById(@PathVariable Integer id, RedirectAttributes attributes) {
        int i = typeService.deleteTypeById(id);
        attributes.addFlashAttribute("message","恭喜您，删除成功");
        return "redirect:/admin/types/1";
    }


}















